<template>
  <div class="videos-container">
    <!-- 表单区域 -->
    <el-form :model="form" ref="form" :rules="rules" label-width="120px" class="videos-form">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="视频标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入视频标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="视频链接" prop="url">
            <el-input v-model="form.url" placeholder="请输入视频链接" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 操作按钮 -->
      <div class="form-footer">
        <el-button type="primary" @click="saveVideo" v-if="!isEditing" v-hasPermi="['degree:videos:add']">添加视频</el-button>
        <el-button type="success" @click="updateVideo" v-if="isEditing" v-hasPermi="['degree:videos:edit']">更新视频</el-button>
        <el-button @click="resetForm" v-if="isEditing">取消编辑</el-button>
      </div>
    </el-form>

    <!-- 视频列表 -->
    <div class="videos-list">
      <el-table :data="videosList" v-loading="loading" border style="width: 100%" max-height="400" empty-text="暂无视频数据，请先添加视频信息">
        <el-table-column type="index" width="50" label="#" align="center" />
        <el-table-column prop="title" label="视频标题" align="center" min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.title">{{ scope.row.title }}</span>
            <span v-else style="color: #999">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="视频链接" align="center" min-width="300" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.url">{{ scope.row.url }}</span>
            <span v-else style="color: #999">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="primary" 
              @click="editVideo(scope.row)" 
              v-hasPermi="['degree:videos:edit']">编辑</el-button>
            <el-button 
              size="mini" 
              type="danger" 
              @click="deleteVideo(scope.row)" 
              v-hasPermi="['degree:videos:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="data-info" style="margin-top: 10px; padding: 10px; background: #f5f7fa; border-radius: 4px; font-size: 14px; color: #666;">
        <span>共找到 {{ videosList.length }} 条视频记录（当前院校：{{ schoolId }}）</span>
        <span v-if="schoolId" style="margin-left: 20px;">当前编辑院校ID: {{ schoolId }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { listVideos, getVideos, addVideos, updateVideos, delVideos } from "@/api/degree/videos"

export default {
  name: "Videos",
  props: {
    schoolId: {
      type: Number,
      required: true
    },
    parentForm: {
      type: Object,
      default: () => ({})
    },
    activeTabName: {
      type: String,
      default: '0'
    }
  },
  data() {
    return {
      loading: false,
      saving: false,
      isEditing: false,
      editingVideoId: null,
      form: {
        id: null,
        schoolId: 0,
        title: '',
        url: '',
        isEnabled: 1
      },
      rules: {
        title: [
          { required: true, message: '请输入视频标题', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入视频链接', trigger: 'blur' }
        ]
      },
      videosList: []
    }
  },
  watch: {
    schoolId: {
      immediate: true,
      handler(newVal, oldVal) {
        this.getVideosList()
      }
    }
  },
  methods: {
    /** 获取视频列表 */
    getVideosList() {
      this.loading = true
      
      const queryParams = {
        pageNum: 1,
        pageSize: 1000,
        schoolId: this.schoolId, // 添加院校ID过滤
        orderByColumn: 'school_id',
        isAsc: 'desc'
      }
      
      listVideos(queryParams).then(response => {
        this.loading = false
        const rawData = response.rows || response.data || []
        this.videosList = this.validateAndFixData(rawData)
      }).catch(error => {
        this.loading = false
        this.videosList = []
        
        // 处理字符串类型的错误
        if (typeof error === 'string') {
          if (error === 'error') {
            this.$message.error("获取视频列表失败：后端接口异常")
          } else {
            this.$message.error("获取视频列表失败：" + error)
          }
          return
        }
        
        // 检查是否是权限相关错误
        if (error?.response?.status === 403 || error?.message?.includes('权限')) {
          this.$message.error("获取视频列表失败：没有访问权限")
        } else if (error?.response?.status === 401) {
          this.$message.error("获取视频列表失败：身份认证已过期，请重新登录")
        } else if (!error?.message && !error?.status) {
          this.$message.error("获取视频列表失败：网络异常或请求被拦截")
        } else {
          this.$message.error("获取视频列表失败：" + (error?.msg || error?.message || '未知错误'))
        }
      })
    },

    /** 数据验证和修正 */
    validateAndFixData(dataList) {
      if (!Array.isArray(dataList)) {
        return []
      }
      
      return dataList
        .filter(item => !this.schoolId || item.schoolId === this.schoolId) // 过滤当前院校数据
        .map((item) => {
          return {
            ...item,
            id: item.id || null,
            schoolId: item.schoolId || this.schoolId,
            title: item.title || '',
            url: item.url || '',
            isEnabled: item.isEnabled !== undefined ? item.isEnabled : 1
          }
        })
    },

    /** 保存视频 */
    saveVideo() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.saving = true
          
          const formData = {
            ...this.form,
            schoolId: this.schoolId
          }
          
          addVideos(formData).then(response => {
            this.saving = false
            this.$message.success("视频添加成功")
            this.resetForm()
            this.getVideosList()
          }).catch(error => {
            this.saving = false
            this.$message.error("视频添加失败：" + (error.msg || error.message || '未知错误'))
          })
        }
      })
    },

    /** 更新视频 */
    updateVideo() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.saving = true
          
          const formData = {
            ...this.form,
            id: this.editingVideoId,
            schoolId: this.schoolId
          }
          
          updateVideos(formData).then(response => {
            this.saving = false
            this.$message.success("视频更新成功")
            this.resetForm()
            this.getVideosList()
          }).catch(error => {
            this.saving = false
            this.$message.error("视频更新失败：" + (error.msg || error.message || '未知错误'))
          })
        }
      })
    },

    /** 编辑视频 */
    editVideo(row) {
      this.isEditing = true
      this.editingVideoId = row.id
      this.form = {
        id: row.id,
        schoolId: row.schoolId,
        title: row.title,
        url: row.url,
        isEnabled: row.isEnabled
      }
    },

    /** 删除视频 */
    deleteVideo(row) {
      this.$confirm('确认删除该视频吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delVideos(row.id).then(response => {
          this.$message.success("视频删除成功")
          this.getVideosList()
        }).catch(error => {
          this.$message.error("视频删除失败：" + (error.msg || error.message || '未知错误'))
        })
      }).catch(() => {})
    },

    /** 重置表单 */
    resetForm() {
      this.isEditing = false
      this.editingVideoId = null
      this.form = {
        id: null,
        schoolId: this.schoolId,
        title: '',
        url: '',
        isEnabled: 1
      }
      
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },

    /** 检查是否有未保存的数据 - 为主页面提供 */
    hasUnsavedData() {
      return false
    },

    /** 保存当前数据 - 为主页面提供 */
    async saveCurrentData() {
      return Promise.resolve(true)
    },

    /** 获取当前组件状态 - 为主页面提供 */
    getComponentStatus() {
      return {
        hasData: this.videosList.length > 0,
        schoolId: this.schoolId,
        dataCount: this.videosList.length
      }
    }
  }
}
</script>

<style scoped>
.videos-container {
  width: 100%;
}

.videos-form {
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 20px;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.videos-list {
  width: 100%;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-button + .el-button {
  margin-left: 8px;
}
</style>
